import json

import execjs
import requests
from bs4 import BeautifulSoup


def fetch_html(url):
    headers = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
        'Pragma': 'no-cache',
        'Referer': 'https://music.163.com/',
        'Sec-Fetch-Dest': 'iframe',
        'Sec-Fetch-Mode': 'navigate',
        'Sec-Fetch-Site': 'same-origin',
        'Sec-Fetch-User': '?1',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0',
        'sec-ch-ua': '"Not)A;Brand";v="99", "Microsoft Edge";v="127", "Chromium";v="127"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
    }

    response = requests.get(url, headers=headers)

    soup = BeautifulSoup(response.text, 'html.parser')
    data = soup.find('textarea', id='song-list-pre-data').getText()
    data = json.loads(data)
    for e in data:
        download(e['name'], e['id'])


def download(name, id):
    headers = {
        'Accept': '*/*',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Origin': 'https://music.163.com',
        'Pragma': 'no-cache',
        'Referer': 'https://music.163.com/',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-origin',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 Edg/128.0.0.0',
        'sec-ch-ua': '"Chromium";v="128", "Not;A=Brand";v="24", "Microsoft Edge";v="128"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
    }

    params = {
        'csrf_token': '',
        'encodeType': "aac",
        'ids': "[" + str(id) + "]",
        'level': "standard"
    }

    data = json.loads(
        execjs.compile(open('main.js', 'r', encoding='utf-8').read()).call('encodeData', json.dumps(params)))

    response = requests.post(
        'https://music.163.com/weapi/song/enhance/player/url/v1',
        params=params,
        headers=headers,
        data=data
    )
    try:
        print(response.json())
        url = response.json()['data'][0]['url']
        ext = url.split(".")[-1]
        response = requests.get(url, headers=headers)
        print(name, url)
        with open("音乐文件" + "/" + name + '.' + ext, mode='wb') as f:
            f.write(response.content)
    except Exception as e:
        print(e)


if __name__ == '__main__':
    fetch_html('https://music.163.com/discover/toplist')
